package mammuthus.controller

import com.google.inject.Inject
import mammuthus.master.Master
import net.csdn.common.env.Environment
import net.csdn.modules.http.{ViewType, RestRequest, ApplicationController}
import net.csdn.annotation.rest.{State, BasicInfo, At}
import mammuthus.controller.filter.{TokenAuthFilter, AppNameCheckFilter}

/**
 * 6/9/15 WilliamZhu(allwefantasy@gmail.com)
 */
class ScriptController @Inject()(akkaMaster: Master, env: Environment) extends ApplicationController with TokenAuthFilter with AppNameCheckFilter{

  @At(path = Array("/script/explain"), types = Array(RestRequest.Method.GET, RestRequest.Method.POST))
  @BasicInfo(
    desc = "",
    state = State.alpha,
    testParams = "?script=",
    testResult = "",
    author = "WilliamZhu",
    email = "allwefantasy@gmail.com"
  )
  def scriptExplain = {

    auth()

    var hahahah = param("script")
    "%sys\\.\\w+[\\.\\w+]*%".r.findAllMatchIn(hahahah).map(f=>f.group(0)).map{f=>
      val sysAndAppNameAndModule = f.replaceAll("%","").split("\\.")
      val Array(s,appName,module) = if(sysAndAppNameAndModule.length==3)sysAndAppNameAndModule else {
        Array(sysAndAppNameAndModule(0),sysAndAppNameAndModule(1),sysAndAppNameAndModule(1))
      }
      (f,akkaMaster.findHostAndPortByAppName(appName,module))
    }.foreach{ f=>
      hahahah = hahahah.replace(f._1,f._2.mkString(","))
    }

    render(200,hahahah,ViewType.string)

  }

}
